package models

import (
	"LazyPig/database"
	"LazyPig/pkg"
	"encoding/json"
	_"fmt"
	"io/ioutil"

	//"LazyPig/pkg/gredis"
	"errors"
	"net/http"
)

type User struct {
	NickName	string	`form:"nickName" binding:"required"`
	Avatar	string	`form:"avatarUrl" binding:"required"`
	Code	string	`form:"code" binding:"required"`
}

type body struct {
	Openid	string	`json:"openid"`
}

func Login(u *User)	(interface{} , error)   {
	response, err := http.Get("https://api.weixin.qq.com/sns/jscode2session?appid=wx11c465a3f7782b4b&secret=742b97f2d855653b2e6422496f004839&grant_type=authorization_code&js_code=" + u.Code)
	defer response.Body.Close()
	if err != nil {
		return nil, errors.New("登录失败")
	}
	if response.StatusCode == 200 {
		data,_ := ioutil.ReadAll(response.Body)
		var res body
		json.Unmarshal(data, &res)
		userInfo := make(map[string]interface{})
		userInfo["nick_name"] = u.NickName
		userInfo["avatar_url"] = u.Avatar
		userInfo["openid"] = res.Openid
		row, err := database.SqlDB.GetOne("SELECT id FROM user WHERE openid = ?", userInfo["openid"])
		if err != nil {
			return nil, errors.New("登录失败")
		}
		if row["id"] != nil {
			token := pkg.CreatedToken(row["id"])
			return token, nil
		} else {
			// 无用户 注册
			user, err := database.SqlDB.Insert("user", userInfo)
			if err != nil {
				return nil, errors.New("登录失败")
			}
			token := pkg.CreatedToken(user)
			return token, nil
		}
	}
	return nil, errors.New("登录失败")
}

func GetUserInfo(uid float64) (interface{}, error)  {
	row, err := database.SqlDB.GetOne("SELECT * FROM user WHERE id = ?", uid)
	if err != nil {
		return nil, err
	}
	return row, err
}

func GetPersonnel() (interface{}, error)  {
	rows, err := database.SqlDB.GetAll("SELECT id, nick_name FROM user")
	if err != nil {
		return nil, errors.New("查询失败")
	}
	return rows, nil
}